<template>
    <v-chart class="chart" :autoresize="true" :loading="loading" :option="data" :theme="props.theme" />
</template>

<script setup>
import {ref, watchEffect} from 'vue';
import {use, graphic} from 'echarts/core';
import VChart from 'vue-echarts';
import {CanvasRenderer} from 'echarts/renderers';
import {PieChart, BarChart, LineChart, ScatterChart, MapChart, EffectScatterChart} from 'echarts/charts';
import {
    TitleComponent,
    TooltipComponent,
    GridComponent,
    GeoComponent,
    LegendComponent,
    MarkPointComponent,
    MarkLineComponent,
    VisualMapComponent,
    PolarComponent,
} from 'echarts/components';

import _ from 'lodash';

use([
    PolarComponent,
    ScatterChart,
    EffectScatterChart,
    CanvasRenderer,
    PieChart,
    LineChart,
    BarChart,
    MapChart,
    GeoComponent,
    TitleComponent,
    GridComponent,
    TooltipComponent,
    LegendComponent,
    MarkLineComponent,
    MarkPointComponent,
    VisualMapComponent,
]);

const props = defineProps({
    theme: {
        type: String,
        default: 'default',
    },
    option: {
        type: Object,
        default: () => ({}),
    },
});

const loading = ref(true);
const data = ref({});

const handleInit = () => {
    let newOption = _.cloneDeep(props.option);
    if (!_.isEmpty(newOption.color)) {
        newOption.color = newOption.color.map(item => {
            const isObject = _.isObject(item);
            const isArray = _.isArray(item);
            const isStr = _.isString(item);

            if (isObject && isArray && [2, 3].includes(item.length)) {
                const start = item[0];
                const end = item[1];
                const direction = item?.[2] || [0, 0, 0, 1];
                return new graphic.LinearGradient(...direction, [
                    {offset: 0, color: start}, // 渐变起始颜色
                    {offset: 1, color: end}, // 渐变结束颜色
                ]);
            } else if (isObject && !isArray) {
                return item;
            } else if (isStr) {
                return item;
            }
        });
    }
    data.value = newOption;
    loading.value = false;
};

watchEffect(handleInit);
</script>

<style scoped>
.chart {
    width: 100%;
    height: 400px;
}
</style>
